/**
 * Created by litong on 15-7-30.
 */
var path = require('path');
var ffmpeg = require('fluent-ffmpeg');
var config = require('../config');
var mkdirp = require('mkdirp');
var fs = require('fs');

//  /root/guoxy/package/ffmpeg-0.6.7/ffmpeg -r 20 -b 1M -i ./res/%d.png -i ./audio.mp3 -vcodec mpeg4 ./video.avi
var I2V = {
    /**
     * 将图片，音频转换为视频的方法
     * @param callback  转换后的回调
     */
    convert : function(callback){
        mkdirp(path.join(config.tmpPath, 'output'), function(err) {
            if(err){
                callback(err);
                return;
            }

            var audioPath = "";
            var rsPath = config.originPath;
            if(fs.existsSync(path.join(rsPath, 'audio'))){
                rsPath = path.join(rsPath, 'audio');
            }
            if(fs.existsSync(path.join(rsPath, 'audio.aac'))){
                audioPath = path.join(rsPath, 'audio.aac');
            }else if(fs.existsSync(path.join(rsPath, 'audio.mp3'))){
                audioPath = path.join(rsPath, 'audio.mp3');
            }else if(fs.existsSync(path.join(rsPath, 'audio.ogg'))){
                audioPath = path.join(rsPath, 'audio.ogg');
            }else if(fs.existsSync(path.join(rsPath, 'audio.caf'))){
                audioPath = path.join(rsPath, 'audio.caf');
            }else{
                cb(new Error("音频文件没有找到"));
            }
            ffmpeg()
                //添加图片.输入帧数
                .addInput(path.join(config.tmpPath, 'imageData','%d.jpg')).inputFPS(25)
                //添加音频
                .addInput(audioPath)
                // 输出帧数
                .fps(25)
                //比特率
                .videoBitrate('1024k')
                .size(config.screenWidth + 'x' + config.screenHeight)
                //视频编码
                .videoCodec('libx264')
                //事件回调
                .on('end', function() {
                    callback();
                })
                .on('error', function(err) {
                    callback(err);
                })
                .on('progress', function(progress) {
                    console.log('转换视频中: ' + progress.percent + '%');
                })
                //保存路径
                .save(path.join(config.tmpPath, 'output','video.mp4'));
        });
    }
}

module.exports = I2V;